import * as React from 'react'
import { Skeleton, Switch, Card, Avatar, Row, Col, message, Popconfirm, Modal, Pagination } from 'antd';

import { useSelector } from 'react-redux'
import api from '../../../api'
import icon from '../../../config/iconConfig'
import EditArt from '../../../components/content/Article/EditArt'
import './index.scss'

const IconFont = icon.icon()

const SearchArticle = () => {
    const [loading, setLoading] = React.useState(false)
    const [data, setData] = React.useState()
    const [isModalVisible, setIsModalVisible] = React.useState(false)
    const [articleId, setArticleId] = React.useState('')
    const okRef = React.useRef()
    const { Meta } = Card;
    const userState = useSelector(state => state.user);
    // const dispatch = useDispatch();

    const handleSwitch = checked => {
        setLoading(!checked);
    };

    const handleDeleConfirm = (article_id) => {
        return async () => {
            const res = await api.article.delArticle({ article_id })
            if (res.data.status === 0) {
                message.success("删除成功");
                console.log(res.data);
                const newData = data.filter(item => {
                    return item.article_id !== article_id
                })
                setData(newData)
            } else {
                message.error(res.data.msg);
            }
        }
    }

    const handleEditClick = (article_id) => {
        return async () => {
            setIsModalVisible(true)
            setArticleId(article_id)
        }
    }

    const handleCancel = () => {
        setIsModalVisible(false);
    };

    const handleOk = () => {
        setIsModalVisible(false);
        let value = okRef.current.getFieldsValue(true)
        const fileList = value.images ? value.images.fileList : null
        const a_user_id = JSON.parse(userState.data)[0].userid
        const creat_time = new Date().toLocaleString();
        const content = value.content ? value.content.toHTML() : null
        value = { ...value, creat_time, images: fileList ? fileList[0].url : '', a_user_id, content, articleId }
        console.log(value);
        api.article.editArticle(value).then(res => {
            console.log(res);
            if (res.data.status === 0) {
                message.success("文章修改成功");
                const newData = data.map(item => {
                    if (item.article_id === articleId) {
                        let descc = value.desc ? value.desc : item.descc;
                        let title = value.title ? value.title : item.title;
                        let content = value.content ? value.content : item.content;
                        return item = { ...item, creat_time: value.creat_time, descc, title, content }
                    } else {
                        return item
                    }
                })
                console.log(newData);
                setData(newData)
            } else {
                message.error(res.data.msg);
            }
        })
    }

    const pageChange = async (page,pageSize) => {
        console.log(page,parseInt(pageSize));
        const a_user_id = JSON.parse(userState.data)[0].userid
        console.log(a_user_id);
        const articleData = await api.article.data({a_user_id,pageNo:page,pageSize:pageSize})
        if (articleData.data.status === 0) {
            message.success("数据获取成功");
            console.log(articleData.data);
            setData(articleData.data.data)
        } else {
            message.error(articleData.data.msg);
        }
    }

    React.useEffect(() => {
        async function fetchData() {
            const a_user_id = JSON.parse(userState.data)[0].userid
            console.log(a_user_id);
            const articleData = await api.article.data({a_user_id})
            if (articleData.data.status === 0) {
                message.success("数据获取成功");
                console.log(articleData.data);
                setData(articleData.data.data)
            } else {
                message.error(articleData.data.msg);
            }

        }
        fetchData()

    }, [userState.data])

    return (
        <div className='search-article'>
            <Row justify='center'>
                <Col span={20}>
                    <label>显示转换：<Switch checked={!loading} onChange={handleSwitch} /></label>
                    {data ? data.map(item => {
                        return (
                            <div key={item.article_id}>
                                <Card
                                    className='search-article-item'
                                    actions={[
                                        <Popconfirm
                                            title="确定删除吗?"
                                            onConfirm={handleDeleConfirm(item.article_id)}
                                            okText="Yes"
                                            cancelText="No"
                                        >
                                            <IconFont type="icon-shanchu" />,
                                    </Popconfirm>,
                                        <IconFont type="icon-bianji" onClick={handleEditClick(item.article_id)} />,
                                        <IconFont type="icon-shenglvehao" />,
                                    ]}
                                    title={`User：${item.username}`}
                                    description="This is the description"
                                >
                                    <Skeleton loading={loading} avatar active>
                                        <Meta
                                            className='content-meta'
                                            avatar={
                                                <Avatar src={item.avatar} />
                                            }
                                            title={item.title}
                                            description={`描述：${item.descc}`}
                                        />
                                        <p className='time'>发布时间：{item.creat_time}</p>
                                        <p className='title'>正文：</p>
                                        <div className="search-article-item-text" id="article-content">
                                            <div dangerouslySetInnerHTML={{ __html: item.content }}></div>
                                            <img src={item.images} style={{ height: '100px', width: '100px' }} alt="" />
                                        </div>
                                    </Skeleton>
                                </Card>
                            </div>
                        )
                    }) : null}
                    <Row justify='center'>
                        <Pagination
                            className='article-page'
                            total={data?JSON.parse(data[0]?data[0].articleCount:1):1}
                            showSizeChanger
                            showQuickJumper
                            defaultCurrent='1'
                            defaultPageSize='5'
                            pageSizeOptions={[5, 10, 20, 50, 100]}
                            showTotal={total => `总共 ${total} 篇`}
                            onChange={pageChange}
                        />
                    </Row>
                </Col>
            </Row>
            <Modal title="编辑文章" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel} maskStyle={{ background: 'raba(0,0,0,0.2)' }}>
                <EditArt props={articleId} ref={okRef}></EditArt>
            </Modal>
        </div>
    )
}

export default SearchArticle